<script setup lang="ts">
import { ref, reactive } from 'vue'
import { useMessage, NForm } from 'naive-ui'

import useComponentRef from '@/hooks/useComponentRef'

const message = useMessage()
const formRef = useComponentRef(NForm)
const sendLoading = ref(false)

interface FormValue {
  email?: string | null
  message: string
}

const formValue: FormValue = reactive({
  email: null,
  message: '',
})

const emit = defineEmits<{
  (e: 'close'): void
}>()

const handleSend = async () => {
  if (!formRef.value) return
  try {
    // 1. 前端验证表单
    await formRef.value.validate()
    sendLoading.value = true
    // 2. 准备请求参数（JSON格式）
    const submitData = { ...formValue } // 复制表单数据
    const targetUrl = 'https://formspree.io/f/mnnbrvqn' // 目标地址

    // 3. 发送POST请求（指定JSON格式）
    const response = await fetch(targetUrl, {
      method: 'POST',
      headers: {
        Accept: 'application/json',
      },
      body: JSON.stringify(submitData), // 将数据转为JSON字符串
    })

    // 4. 处理响应
    sendLoading.value = false
    if (response.ok) {
      const result = await response.json()
      message.success('提交成功！')
      console.log('服务器响应：', result)
      // 清空表单
      formValue.email = null
      formValue.message = ''
      emit('close')
    } else {
      throw new Error(`提交失败：${response.statusText}`)
    }
  } catch (error) {
    console.error('提交出错：', error)
  }
}

const handleClose = () => {
  emit('close')
}
</script>

<template>
  <n-card title="反馈" class="feedback-form-card" content-style="overflow-y:auto" closable hoverable @close="handleClose">
    <n-form ref="formRef" :model="formValue" :rules="{
      message: [
        {
          required: true,
          message: '请输入反馈内容',
          trigger: ['blur', 'input'],
        },
      ],
    }">
      <n-form-item label="你的邮箱" path="email">
        <n-input type="text" v-model:value="formValue.email" placeholder="你的邮箱或者别的联系方式" />
      </n-form-item>
      <n-form-item label="你想说的" required path="message">
        <n-input type="textarea" v-model:value="formValue.message" placeholder="感谢你的反馈与建议" />
      </n-form-item>
      <n-form-item>
        <n-button @click="handleSend" :disabled="!formValue.message" :loading="sendLoading">Send</n-button>
      </n-form-item>
    </n-form>
  </n-card>
</template>

<style scoped></style>
